<template>
    <div class="MusicRadio">
        <div class="left" v-show="playingList.length">
            <transition name="imgpng">
                <div v-show="Main.detailStatus == 'close'">
                    <div class="image" @mouseover="musicDetail" @mouseout="musicDetailLeave" title="展开音乐详情页"
                        @click="showDetail">
                        <el-image draggable="false" :src="playingList[playingindex - 1]?.al?.picUrl" fit="cover">
                        </el-image>
                        <div class="mask">
                            <i class="iconfont icon-xialajiantou1" v-if="Main.songType !== 'FM'"></i>
                            <i class="iconfont icon-shangxiajiantou" v-else></i>
                        </div>
                    </div>
                    <div class="txt">
                        <div class="t">
                            <div class="name" @mouseover="rushName('nameTxt')">
                                <div class="name-txt" id="nameTxt">{{ playingList[playingindex - 1]?.name }}
                                    <span class="small" v-if="playingList[playingindex - 1]?.tns?.length">&nbsp;({{
                                            playingList[playingindex - 1]?.tns[0]
                                    }})</span>
                                    <span class="small"
                                        v-else-if="playingList[playingindex - 1]?.alia?.length">&nbsp;({{
                                                playingList[playingindex - 1]?.alia[0]
                                        }})</span>
                                </div>
                            </div>
                            <i v-if="likeFlag" class="iconfont icon-aixin" @click="likeOrDislike"></i>
                            <i v-else class="iconfont icon-aixin_fill" @click="likeOrDislike"></i>
                        </div>
                        <div class="singer" @mouseover="rushSinger('singerTxt')">
                            <span id="singerTxt">
                                <span v-for="(value, index) in playingList[playingindex - 1]?.ar"
                                    :key="playingList[playingindex - 1]?.ar[index]?.id"
                                    :id="playingList[playingindex - 1]?.ar[index]?.id">
                                    {{ playingList[playingindex - 1]?.ar[index].name }}
                                    <span v-if="index != playingList[playingindex - 1]?.ar.length - 1" style="transform: rotate(-10deg) translateY(-2px);
                        display: inline-block;
                        font-size: 10px;
                        padding-right: 3px;
                        ">/</span>
                                </span>
                            </span>
                        </div>
                    </div>
                </div>
            </transition>
            <transition name="option">
                <div v-show="Main.detailStatus == 'open'" class="showOption">
                    <div class="left" @click="showDetail">
                        <i class="iconfont icon-xiangxiajiantou"></i>
                    </div>
                    <div class="right">
                        <!-- :likeJust()?'icon-aixin_fill':'icon-aixin' -->
                        <div class="todo" @click="likeOrDislike" :class="{ noDrag: !Main.dragMouse }">
                            <i v-if="likeFlag" class="iconfont icon-aixin"></i>
                            <i v-else class="iconfont icon-aixin_fill"></i>
                        </div>
                        <div class="todo" v-for="(value, index) in 3" :class="{ noDrag: !Main.dragMouse }">
                            <i class="iconfont" :class="[leftIcon[index + 1]]"></i>
                        </div>
                    </div>
                </div>
            </transition>

        </div>
        <div class="readioOption">
            <div class="top" ref="top">
                <div class="way">
                    <transition leave-active-class="animate__animated animate__fadeOut"
                        enter-active-class="animate__animated animate__fadeIn">
                        <SmallTips v-if="showPlayWay" @close="showPlayWay = false" :message="iconWayWrite[wayIndex]">
                        </SmallTips>
                    </transition>

                    <i class="iconfont" :class="[iconWay[wayIndex]]" :title="iconWayWrite[wayIndex]" @click="nextWay"
                        v-if="Main.songType !== 'FM'"></i>
                    <i class="iconfont icon-lajixiang" v-else title="垃圾桶" @click="rubish"></i>
                </div>
                <div class="before" @click="prevSongThor" title="上一首（Ctrl + Left）">
                    <i class="iconfont icon-shangyishou"></i>
                </div>
                <div class="start">
                    <div class="bk" @click="changPlayStatus" :title="`${stopOrPlayFlag ? '继续' : '暂停'}（Ctrl + P）`">
                        <i class="iconfont icon-gf-play" v-if="stopOrPlayFlag"></i>
                        <i class="iconfont icon-zanting" v-else></i>
                    </div>
                </div>
                <div class="next" @click="nextSongThor" title="下一首（Ctrl + Right">
                    <i class="iconfont icon-xiayishou"></i>
                </div>
                <div class="ci" @click="openCi" ref="ci">
                    <i class="iconfont icon-geciweidianji"></i>
                    <i class="iconfont icon-openci-copy" v-if="showCi"></i>
                </div>
            </div>
            <div class="bottom">
                <div class="number-before">{{ nowTime }}</div>
                <div class="audio-line" @click="clickAudioPlay">
                    <div class="line-loading" v-show="playingList.length"></div>
                    <div class="line-play" v-show="playingList.length"></div>
                    <div class="block" v-show="playingList.length" @mousedown="audioPlay"></div>
                </div>
                <div class="number-end">{{ endTime }}</div>
            </div>
        </div>
        <div class="right" v-show="playingList.length">
            <div class="playLevel" id="playLevel" draggable="false" @click="showLevel">
                <SmallBlock v-if="showLevelFlag" :id="114514" :if-level="true"
                    :max-have="playingPrivileges[playingindex - 1].maxBrLevel"
                    :max-level="playingPrivileges[playingindex - 1].plLevel" :now-level="nowLevel"
                    @show="changeSpanLevel" @close="showLevelFlag = false"></SmallBlock>
                <div class="bk">
                    <span draggable="false">{{ levelName }}</span>
                </div>
            </div>
            <div class="playSpeed" id="playSpeed" draggable="false" @click="showSpeed">
                <SmallBlock v-if="showSpeedFlag" :id="114514" :width="110" :height="170" :speedPower="speedPower"
                    @close="showSpeedFlag = false" @show="changeSpanSpeed"></SmallBlock>
                <div class="bk">
                    <span draggable="false">{{ speedPower == '1x' ? '倍速' : speedPower }}</span>
                </div>
            </div>
            <div class="shengyin" @mouseenter="changeShenYing" @mouseleave="endShenYing">
                <i class="iconfont icon-shengyin" @click="Mute" v-if="MuteFlag"></i>
                <i class="iconfont icon-shengyinguanbi" @click="Mute" v-else></i>
                <div class="shengyin-line" v-show="changeShengYing">
                    <div class="hua" @click="immediateChamgeYingLiang">
                        <div class="liang">
                            <div class="point" @mousedown="beginMove"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="playList" id="playlistIcon" v-show="Main.songType != 'FM'">
                <i class="iconfont icon-24gf-playlist" @click="showPlayListPanel"></i>
                <div v-show="PlayListPanelFlag">
                    <PlayListPanel @close="PlayListPanelFlag = false" @stopPlay="clearList"></PlayListPanel>
                </div>
            </div>
        </div>
        <audio :src="SongUrl"></audio>
        <PlayingPointOut v-if="globalVar.closePointOut" @close="globalVar.closePointOut = false"
            :message="globalVar.closePointOutMessage"></PlayingPointOut>
    </div>
    <div v-if="offsetFlag">
        <Loading :loading="false" :message="lyricOffset + 's'" :showTime="1000" @close="offsetFlag = false" width="50">
        </Loading>
    </div>
    <transition name="songDetail">
        <SongDetail :currentTime="currentTime" :lyricOffset="lyricOffset" :simiSong="simiSong"
            :simiPlaylist="simiPlaylist" @goTotime="goTotime"></SongDetail>
    </transition>
    <Teleport to="body">
        <Loading :loading="false" v-if="loadingFlag" @close="loadingFlag = false" :showTime="1500"
            :message="likeMessage"></Loading>
    </Teleport>
</template>

<script lang="ts" setup>
import {
    ref, onMounted, getCurrentInstance, ComponentInternalInstance,
    Ref, nextTick, toRef, watch, shallowRef
} from 'vue'
import { dayjsSMMSS } from '@/utils/dayjs';
import { throttle } from 'lodash'
import { useMain, useGlobalVar } from '@/store';
import { rand } from '@/utils/rand';
import { useRouter } from 'vue-router';
import { useElectronToApp } from '@/store/index'
import PlayListPanel from './playListPanel/index.vue';
import SongDetail from './SongDetail/index.vue';
const $el = getCurrentInstance() as ComponentInternalInstance;
const Main = useMain();
const globalVar = useGlobalVar();
const ElectronToApp = useElectronToApp()
const $router = useRouter();
let iconWay = ref(['icon-caozuo-xunhuan1', 'icon-danquxunhuan', 'icon-xunhuanbofang', 'icon-shunxubofang'])
const leftIcon = ['icon-aixin', 'icon-wodeshoucang', 'icon-xiazai1', 'icon-fenxiang']
let iconWayWrite = ref(['列表循环', '单曲循环', '随机播放', '顺序播放'])
const ciId = electronIpc.ipcSendSync('getWindowId', 'Ci');


let playingList = toRef(Main, 'playingList')
let playingPrivileges = toRef(Main, 'playingPrivileges')
let playingId = toRef(Main, 'playing')
let playingindex = toRef(Main, 'playingindex')
let likes = toRef(Main, 'likes');
let likesLength = toRef(Main.likes, 'length')
let randQueue: Array<number> = [];
let randIndex = ref(-1);

let stopOrPlayFlag: Ref<Boolean> = ref(true)
let wayIndex = toRef(Main, 'wayIndex');
let showCi = ref(false);
let MuteFlag = ref(true);
let audio: HTMLAudioElement
let loadingLine: HTMLElement
let playLine: HTMLElement;
let playBall: HTMLElement;
let line: HTMLElement
let audioPlayFlag = ref(false)
let lyric: Ref<Object> = shallowRef({});
let offsetFlag = ref(false)
let SongUrl = ref('')
let nowTime = ref(dayjsSMMSS(0))
let endTime = ref(dayjsSMMSS(0))
let playListId = toRef(Main, 'beforePlayListId')


//喜欢和取消喜欢
let likeFlag = ref(false)
//true 是爱心 false 是填充爱心
watch(likesLength, () => {
    if (likes.value.includes(playingId.value)) {
        likeFlag.value = false
    } else {
        likeFlag.value = true
    }
})

watch(playingId, () => {
    if (likes.value.includes(playingId.value)) {
        likeFlag.value = false
    } else {
        likeFlag.value = true
    }
})

let likeMessage = ref('')
let loadingFlag = ref(false)
const likeOrDislike = () => {
    let likeIndex = likes.value.indexOf(playingId.value)
    if (likeIndex != -1) {
        //取消喜欢
        Main.reqLike(Number(playingId.value), false)
        likes.value.splice(likeIndex, 1)
        likeMessage.value = '取消喜欢成功'
        loadingFlag.value = true
        Main.likeChange = `${playingId.value},false`
    } else {
        Main.reqLike(Number(playingId.value), true)
        console.log(playingId.value);
        likes.value.unshift(playingId.value)
        likeMessage.value = '已添加到我喜欢的音乐'
        loadingFlag.value = true
        Main.likeChange = `${playingId.value},true`
    }

}

//心动模式
watch(playListId, async () => {
    if (playListId.value == Main.playListId[0]) {
        console.log('展示心动模式图标');
        if (iconWay.value.length != 5) {
            iconWay.value.push('icon-xindong-copy')
            iconWayWrite.value.push('鸡动模式')
        }
        if (Main.wayIndex != 4) {
            originalList.value = playingList.value
            originalPrivileges.value = playingPrivileges.value
            originalsongIndex.value = playingindex.value
        } else {
            let result = (await Main.reqPlaylistTrackAll(playListId.value)).data;
            originalList.value = result.songs
            originalPrivileges.value = result.privileges
            originalsongIndex.value = playingindex.value
        }
    } else {
        Main.wayIndex = 0
        originalList.value = []
        originalPrivileges.value = []
        if (iconWay.value.length == 5) {
            iconWay.value.pop()
            iconWayWrite.value.pop()
        }
    }
})

let originalList = toRef(Main, 'originalList')
let originalPrivileges = toRef(Main, 'originalPrivileges')
let originalsongIndex = toRef(Main, 'originalsongIndex')
watch(wayIndex, async () => {
    if (wayIndex.value == 4) {
        console.log('获取心动模式列表');
        Main.heartJump = true
        let result: Array<any> = (await Main.reqPlaymodeIntelligenceList(playingId.value, Number(playListId.value), playingId.value)).data.data
        console.log(result);
        let idArr = [] as unknown as [number]
        result.forEach((element) => {
            idArr.push(element.id)
        })
        let songList = (await (Main.reqSongDetail(idArr))).data
        let needPlay = playingList.value[playingindex.value - 1]
        let needPlayPrivileges = playingPrivileges.value[playingindex.value - 1]
        playingList.value = songList.songs
        playingPrivileges.value = songList.privileges
        playingList.value.unshift(needPlay)
        playingPrivileges.value.unshift(needPlayPrivileges)
        originalsongIndex.value = playingindex.value
        playingindex.value = 1
    } else if (playListId.value == Main.playListId[0] && wayIndex.value != 4) {
        playingList.value = originalList.value as [any]
        playingPrivileges.value = originalPrivileges.value as [any]
        playingindex.value = originalsongIndex.value
        playingId.value = playingList.value[playingindex.value - 1].id
        Main.heartJump = false

    }
})

//子组件修改播放时间
const goTotime = (time: number) => {
    audio = document.querySelector('audio') as HTMLAudioElement
    console.log(audio, time);

    if (audio) {
        audio.currentTime = time / 1000;
        Main.playStatus = 'play'
    }
}

let changeTimeFlag = toRef(globalVar, 'changeTimeFlag')
watch(changeTimeFlag, () => {
    if (changeTimeFlag.value == true) {
        goTotime(globalVar.timeValue)
        changeTimeFlag.value = false
    }
})

//音乐详情ye
const musicDetail = () => {
    let mask = document.querySelector('.mask') as HTMLElement
    let elimg = mask.previousSibling as HTMLElement
    elimg.classList.add('el-image-hover')
    mask.classList.add('active-flex');
    mask.children[0].classList.add('active');
}

const musicDetailLeave = () => {
    let mask = document.querySelector('.mask') as HTMLElement
    let elimg = mask.previousSibling as HTMLElement
    elimg.classList.remove('el-image-hover')
    mask.classList.remove('active-flex');
    mask.children[0].classList.add('active');
}

const showDetail = () => {
    if (Main.songType == 'FM') {
        $router.push({
            path: '/app/personalFM',
            query: {
                name: 'personalFM'
            }
        })
    } else {
        if (Main.detailStatus == 'close') Main.detailStatus = 'open'
        else Main.detailStatus = 'close'
    }
}

let simiSong = ref<any>()
let simiPlaylist = ref<any>()
//获取播放url
watch(playingId, async () => {
    if (playingId.value != -1) {
        audio = document.querySelector('audio') as HTMLAudioElement
        audio.currentTime = 0
        audio.pause()
        let result: any = await Main.reqSongUrl(playingId.value)
        lyric.value = (await Main.reqLyric(playingId.value)).data
        SongUrl.value = result.data.data[0].url
        nextTick(() => {
            stopOrPlayFlag.value = false
            audio.playbackRate = Number(speedPower.value.substring(0, speedPower.value.length - 1))
            audio.play()
        })
        nowLevel.value = 'standard'
        levelName.value = '标准'
        //喜欢这首歌的人也听与包含这首歌的歌单
        simiSong.value = (await Main.reqSimiSong(playingId.value)).data.songs;
        simiPlaylist.value = (await Main.reqSimiPlaylist(playingId.value)).data.playlists;
        console.log(simiSong, simiPlaylist);
    }
})
// let t = setTimeout(async ()=>{
//             const CiId = await electronIpc.ipcSendSync('getWindowId','Ci');
//             clearTimeout(t);
//             electronIpc.ipcSendTo(CiId, 'to-Ci', lyric);
//         },1000)
watch(lyric, async () => {
    let str = playingList.value[playingindex.value - 1].name + ' - ';
    let singerArr = playingList.value[playingindex.value - 1].ar as unknown as Array<any>
    singerArr.forEach((element, index) => {
        str += element.name
        if (index != singerArr.length - 1) str += ' / '
    })
    electronIpc.ipcSendTo(ciId, 'to-title', str);
    electronIpc.ipcSendTo(ciId, 'to-Ci', lyric.value);
    ElectronToApp.lrcArry = lyric.value

})


//audio初始化
let currentTime = ref<number>(0)
watch(currentTime, () => {
    globalVar.currentTime = currentTime.value
})
watch(playingId, () => {
    globalVar.lyricOffset = 0
    electronIpc.ipcSendTo(ciId, 'lyric-offset-ci', 0)
})

onMounted(async () => {
    audio = document.querySelector('audio') as HTMLAudioElement
    loadingLine = document.querySelector('.line-loading') as HTMLElement
    playLine = document.querySelector('.line-play') as HTMLElement
    playBall = document.querySelector('.block') as HTMLElement
    line = document.querySelector('.audio-line') as HTMLElement
    //加载进度
    audio.addEventListener('progress', () => {
        console.log(audio.duration);
        if (!isNaN(audio.duration)) {
            let timeRanges = audio.buffered;
            // 获取以缓存的时间
            let timeBuffered = timeRanges.end(timeRanges.length - 1);
            // 获取缓存进度，值为0到1
            let bufferPercent = timeBuffered / audio.duration;
            loadingLine.style.width = bufferPercent * 100 + '%'
        }
    })
    //末时间
    audio.addEventListener('canplaythrough', () => {
        endTime.value = dayjsSMMSS(Math.floor(audio.duration))
    })
    //播放进度
    audio.addEventListener('timeupdate', () => {
        if (!audioPlayFlag.value) {
            electronIpc.ipcSendTo(ciId, 'to-currentTime', audio.currentTime);
            currentTime.value = audio.currentTime
            let bar = (audio.currentTime / audio.duration) * 100
            playLine.style.width = bar + '%'
            playBall.style.left = (audio.currentTime / audio.duration) * line.offsetWidth - 4.5 + 'px'
            // console.log((audio.currentTime / audio.duration) * line.offsetWidth - 4.5);
            nowTime.value = dayjsSMMSS(audio.currentTime)
        }
    })
    //播放完毕
    audio.addEventListener('ended', () => {
        console.log('播放完毕');
        stopOrPlayFlag.value = true;
        if (wayIndex.value == 0 || wayIndex.value == 4) {
            nextSongThor()
        } else if (wayIndex.value == 1) {
            audio.play()
            stopOrPlayFlag.value = false
        } else if (wayIndex.value == 2) {
            playingindex.value = rand(1, playingList.value.length, playingindex.value)
            playingId.value = playingList.value[playingindex.value - 1].id
            randQueue.push(playingindex.value)
            randIndex.value++;
        } else if (wayIndex.value == 3) {
            if (playingindex.value == playingList.value.length) {
                audio.pause();
                stopOrPlayFlag.value = true
            } else {
                playingindex.value++;
                playingId.value = playingList.value[playingindex.value - 1].id
            }
        }
    })
})

//点击拖动修改播放位置
let clickX: number;
let baseWidth: number;
const audioPlay = (e: MouseEvent) => {
    audioPlayFlag.value = true;
    clickX = e.pageX;
    window.addEventListener('mousemove', audioPlayMoving)
    window.addEventListener('mouseup', audioPlayEnd)
    playLine = document.querySelector('.line-play') as HTMLElement
    baseWidth = playLine.offsetWidth
}

const audioPlayMoving = (e: MouseEvent) => {
    if (audioPlayFlag.value) {
        let x = e.pageX
        playLine = document.querySelector('.line-play') as HTMLElement
        playBall = document.querySelector('.block') as HTMLElement
        line = document.querySelector('.audio-line') as HTMLElement
        let t;
        if (x > clickX) {
            //右移
            let space = x - clickX;
            t = (baseWidth + space) / line.offsetWidth * 100
            if (t < 0) t = 0;
            else if (t > 100) t = 100;
            playLine.style.width = t + '%'
            t = baseWidth + space - 4.5
            if (t < 0) t = 0;
            else if (t > line.offsetWidth) t = line.offsetWidth;
            playBall.style.left = t + 'px'
        } else {
            //左移
            let space = clickX - x;
            t = (baseWidth - space) / line.offsetWidth * 100
            if (t < 0) t = 0;
            else if (t > 100) t = 100;
            playLine.style.width = t + '%'
            t = baseWidth - space - 4.5
            if (t < 0) t = 0;
            else if (t > line.offsetWidth) t = line.offsetWidth;
            playBall.style.left = t + 'px'
        }
    }

}

let suo = ref(true)
const audioPlayEnd = () => {
    audio = document.querySelector('audio') as HTMLAudioElement
    playLine = document.querySelector('.line-play') as HTMLElement
    let wh = playLine.style.width
    audio.currentTime = Number(wh.substring(0, wh.length - 1)) * audio.duration * 0.01
    audioPlayFlag.value = false;
    suo.value = false
    window.removeEventListener('mousemove', audioPlayMoving)
    window.removeEventListener('mouseup', audioPlayEnd)
}

//点击修改播放
const clickAudioPlay = (e: MouseEvent) => {
    if (playingList.value.length) {
        if (suo.value) {
            audio = document.querySelector('audio') as HTMLAudioElement
            playLine = document.querySelector('.line-play') as HTMLElement
            playBall = document.querySelector('.block') as HTMLElement
            line = document.querySelector('.audio-line') as HTMLElement
            let wh = e.offsetX
            playBall.style.left = wh - 4.5 + 'px'
            playLine.style.width = wh / line.offsetWidth * 100 + '%'
            nowTime.value = dayjsSMMSS(audio.duration * (wh / line.offsetWidth))
            suoFlag.value = true;
            audio.currentTime = wh / line.offsetWidth * audio.duration
        } else {
            suo.value = true;
        }
    }

}

//点击播放按钮
const stopOrPlay = () => {
    if (playingList.value.length !== 0) {
        stopOrPlayFlag.value = !stopOrPlayFlag.value
        if (audio.paused) {
            if (wayIndex.value == 3 && playingindex.value == playingList.value.length) {
                playingindex.value = 1
                playingId.value = playingList.value[playingindex.value - 1].id
            } else {
                audio.play();
                Main.playStatus = 'play'
                electronIpc.ipcSend('render-play')
            }
        } else {
            audio.pause();
            Main.playStatus = 'stop'
            electronIpc.ipcSend('render-play-fail')
        }
    }
}

const changPlayStatus = () => {
    if (playStatus.value == 'play') playStatus.value = 'stop'
    else playStatus.value = 'play'
}


//下一种播放模式
let showPlayWay = ref(false)
const nextWay = () => {
    wayIndex.value++;
    showPlayWay.value = true
    if (wayIndex.value == iconWay.value.length) {
        wayIndex.value = 0
    }
    if (wayIndex.value !== 2) {
        randQueue = [];
        randIndex.value = -1;
    }
}

//打开歌词
const openCi = async () => {
    if (playingList.value.length) {
        showCi.value = !showCi.value
        let dom = $el.refs.ci as HTMLElement
        if (dom.classList.contains('open-ci')) {
            dom.classList.remove('open-ci')
        } else {
            dom.classList.add('open-ci')
        }
        electronIpc.ipcSend('open-lyric', showCi.value)
    }
}
//关闭歌词
electronIpc.ipcOn('to-close-ci', (e: any, flag: [boolean]) => {
    showCi.value = flag[0]
    let dom = $el.refs.ci as HTMLElement
    dom.classList.remove('open-ci')
})
//监视播放给另一个进程
let playStatus = toRef(Main, 'playStatus')
watch(playStatus, async () => {
    electronIpc.ipcSendTo(ciId, 'play-status', playStatus.value)
    stopOrPlay()
}, { immediate: true })
//另一进程play or stop
electronIpc.ipcOn('play-or-stop', () => {
    changPlayStatus();
})
//另一进程上一首
electronIpc.ipcOn('prev-song', () => {
    prevSongThor();
})
//另一进程下一首
electronIpc.ipcOn('next-song', () => {
    nextSongThor();
})
//另一进程歌词偏离
let lyricOffset = toRef(globalVar, 'lyricOffset')
electronIpc.ipcOn('lyric-offset', (e: any, num: [number]) => {
    offsetFlag.value = true
    lyricOffset.value = num[0]
})

//上一首
const prevSong = () => {
    if (Main.songType == 'FM') {
        if (Main.FMindex > 0) {
            Main.FMindex--
        }
    } else {
        originalsongIndex.value++
        if (wayIndex.value == 2) {
            randIndex.value--;
            if (randIndex.value == -1) {
                playingindex.value = rand(1, playingList.value.length, playingindex.value)
                playingId.value = playingList.value[playingindex.value - 1].id
                randQueue.unshift(playingindex.value)
                randIndex.value++;
            }
            playingindex.value = randQueue[randIndex.value]
        } else {
            playingindex.value--
            if (playingindex.value == 0) {
                playingindex.value = playingList.value.length
            }
        }
        playingId.value = playingList.value[playingindex.value - 1].id
        playStatus.value = 'play'
        let str = playingList.value[playingindex.value - 1].name + ' - ';
        let singerArr = playingList.value[playingindex.value - 1].ar as unknown as Array<any>
        singerArr.forEach((element, index) => {
            str += element.name
            if (index != singerArr.length - 1) str += ' / '
        })
        electronIpc.ipcSend('change-play-thum', str)
        electronIpc.ipcSend('render-play')
    }
}
//下一首
const nextSong = () => {
    if (Main.songType == 'FM') {
        Main.FMindex++
    } else {
        originalsongIndex.value++
        if (wayIndex.value == 2) {
            randIndex.value++;
            if (randIndex.value == randQueue.length) {
                let randNum = rand(1, playingList.value.length, playingindex.value)
                playingindex.value = randNum
                playingId.value = playingList.value[playingindex.value - 1].id
                randQueue.push(playingindex.value)
            }
            playingindex.value = randQueue[randIndex.value]
        } else {
            playingindex.value++
            if (playingindex.value == playingList.value.length + 1) {
                playingindex.value = 1
            }
        }
        playingId.value = playingList.value[playingindex.value - 1].id
        playStatus.value = 'play'
        let str = playingList.value[playingindex.value - 1].name + ' - ';
        let singerArr = playingList.value[playingindex.value - 1].ar as unknown as Array<any>
        singerArr.forEach((element, index) => {
            str += element.name
            if (index != singerArr.length - 1) str += ' / '
        })
        electronIpc.ipcSend('change-play-thum', str)
        electronIpc.ipcSend('render-play')
    }

}

const nextSongThor = throttle(nextSong, 1000, { leading: true })
const prevSongThor = throttle(prevSong, 1000, { leading: true })

//audio修改音量
const audioVolume = () => {
    audio = document.querySelector('audio') as HTMLAudioElement
    let value = Number(localStorage.getItem('baseLine')) / 100.0
    console.log(value);
    audio.volume = value;
}


//静音
let stopValue = '0%'
const Mute = () => {
    MuteFlag.value = !MuteFlag.value;
    let t = document.querySelector('.liang') as HTMLElement;
    if (t.style.height != '0%') {
        stopValue = t.style.height
        t.style.height = '0%'
        localStorage.setItem('baseLine', '0')
    } else {
        t.style.height = stopValue
        localStorage.setItem('baseLine', stopValue.substring(0, stopValue.length - 1))
        stopValue = '0%'
    }
    audioVolume();
}

//音量控制
let clickY: number;
let _that: HTMLElement;
let which: HTMLElement;
let bk: HTMLElement
let baseLine: number;
let changeShengYing = ref(false)
const changeShenYing = () => {
    changeShengYing.value = true
}

let movingFlag = ref(false);
const endShenYing = () => {
    if (!movingFlag.value) {
        changeShengYing.value = false
    }
}


const move = (e: MouseEvent) => {
    movingFlag.value = true
    let y = e.pageY;
    baseLine = Number(localStorage.getItem('baseLine'))
    let step;
    if (y < clickY) step = (((clickY - y) / bk.offsetHeight) * 100 + baseLine);
    else step = (baseLine - ((y - clickY) / bk.offsetHeight) * 100)
    // step = ((Math.abs(y - clickY - baseLine)  / bk.offsetHeight) * 100;
    if (step > 100) step = 100
    else if (step < 0) step = 0
    if (step == 0) MuteFlag.value = false;
    else MuteFlag.value = true;
    which.style.height = step + '%'
    audio = document.querySelector('audio') as HTMLAudioElement
    audio.volume = step / 100.0
}


const beginMove = (e: MouseEvent) => {
    if (changeShengYing.value) {
        clickY = e.pageY
        movingFlag.value = true
        _that = e.target as HTMLElement //点击的按钮
        which = _that?.parentNode as HTMLElement     //修改的对象
        bk = which?.parentNode as HTMLElement
        which.style.height = Number(localStorage.getItem('baseLine')) + '%'
        audioVolume();
        window.addEventListener('mousemove', move)
        window.addEventListener('mouseup', movingEnd)
    }
}

const movingEnd = () => {
    movingFlag.value = false
    let str = which.style.height
    localStorage.setItem('baseLine', str.substring(0, str.length - 1))
    audioVolume();
    window.removeEventListener('mouseup', movingEnd)
    window.removeEventListener('mousemove', move)
}
let suoFlag = toRef(globalVar, 'lrcScrollSuo')
//直接修改
const immediateChamgeYingLiang = (e: MouseEvent) => {
    // baseLine = Number(localStorage.getItem('baseLine'))
    // let bar = (e.offsetY / 60) * 100
    // localStorage.setItem('baseLine',bar.toString())
    let dom = e.target as HTMLElement
    if (dom.classList.contains('hua')) {
        //点击灰色部分
        let topSpace = e.offsetY;   //px
        which = dom.children[0] as HTMLElement
        let bottomPer = Number(localStorage.getItem('baseLine')) * 0.8    //%转为px
        let changeWay = 80 - topSpace - bottomPer                   //位移px
        bottomPer = (changeWay + bottomPer) / 80 * 100
        which.style.height = bottomPer + '%'
        localStorage.setItem('baseLine', bottomPer.toString())
    } else if (dom.classList.contains('liang')) {
        //点击彩色部分
        let topSpace = e.offsetY
        let bottomPer = Number(localStorage.getItem('baseLine')) * 0.8
        bottomPer = (bottomPer - topSpace) / 80 * 100
        dom.style.height = bottomPer + '%'
        localStorage.setItem('baseLine', bottomPer.toString())
    }
    audioVolume();
}

//音量控制 初始化
onMounted(() => {
    let dom = document.querySelector('.liang') as HTMLElement
    dom.style.height = Number(localStorage.getItem('baseLine')) + '%'
    if (Number(localStorage.getItem('baseLine')) == 0) {
        MuteFlag.value = false
    } else {
        MuteFlag.value = true
    }
    audioVolume();
})

//禁用播放器
const stopPlayAudip = () => {
    if (playingList.value.length == 0) {
        stopOrPlayFlag.value = true
        nextTick(() => {
            let dom = $el.refs.top as HTMLElement
            dom.classList.add('stop')
            dom.classList.remove('can')
            let [...arr] = dom.children as unknown as Array<HTMLElement>
            arr.forEach((element: HTMLElement) => {
                element.classList.remove('active')
            })
        })

    } else {
        stopOrPlayFlag.value = false
        nextTick(() => {
            let dom = $el.refs.top as HTMLElement
            dom.classList.add('can')
            dom.classList.remove('stop')
            let [...arr] = dom.children as unknown as Array<HTMLElement>
            arr.forEach((element: HTMLElement) => {
                element.classList.add('active')
            })
        })

    }
}
watch(playingList, () => {
    stopPlayAudip();
    if (playingList.value.length == 0) {
        window.removeEventListener('keydown', keyDownWatch)
    } else {
        window.addEventListener('keydown', keyDownWatch)
    }
}, { deep: true })

onMounted(() => {
    stopPlayAudip();
})

//左部名字滚动
let moveNameFlag = ref(true)
let moveSingerFlag = ref(true)
const rushName = (str: string) => {
    let dom = document.querySelector(`#${str}`) as HTMLElement;
    if (moveNameFlag.value && dom.offsetWidth > 150) {
        dom.style.transition = 'transform 10s linear'
        moveNameFlag.value = false
        let father = dom.parentNode;
        father?.appendChild(dom.cloneNode(true))
        let [...arr] = father?.children as unknown as Array<HTMLElement>
        arr.forEach((element: HTMLElement) => {
            let len = element.offsetWidth + 10
            element.style.transform = 'translateX(-' + len + 'px)'
        })
        let time = setTimeout(() => {
            // father?.removeChild(arr[0])
            dom.removeAttribute('style')
            arr[0].removeAttribute('style')
            father?.removeChild(arr[1])
            moveNameFlag.value = true
            clearTimeout(time)
        }, 10000)
    }
}

const rushSinger = (str: string) => {
    let dom = document.querySelector(`#${str}`) as HTMLElement;
    if (moveSingerFlag.value && dom.offsetWidth > 150) {
        dom.style.transition = 'transform 10.5s linear'
        moveSingerFlag.value = false
        let father = dom.parentNode;
        father?.appendChild(dom.cloneNode(true))
        let [...arr] = father?.children as unknown as Array<HTMLElement>
        arr.forEach((element: HTMLElement) => {
            let len = element.offsetWidth + 10
            element.style.transform = 'translateX(-' + len + 'px)'
        })
        let time = setTimeout(() => {
            dom.removeAttribute('style')
            arr[0].removeAttribute('style')
            father?.removeChild(arr[1])
            moveSingerFlag.value = true
            clearTimeout(time)
        }, 10000)
    }
}
//右部音质选择
let showLevelFlag = ref(false)
const showLevel = () => {
    showLevelFlag.value = !showLevelFlag.value
}
//修改音质span
let levelName = ref('标准')
let nowLevel = ref('standard')
const changeSpanLevel = async (level: string, level2: string) => {
    levelName.value = level
    nowLevel.value = level2
    audio = document.querySelector('audio') as HTMLAudioElement
    changPlayStatus();
    let t = audio.currentTime
    let result: any = await Main.reqSongUrl(playingId.value, nowLevel.value)
    nextTick(() => {
        SongUrl.value = result.data.data[0].url
        audio = document.querySelector('audio') as HTMLAudioElement
        audio.playbackRate = Number(speedPower.value.substring(0, speedPower.value.length - 1))
        setTimeout(() => {
            audio.currentTime = t
            changPlayStatus();
        }, 100)
    })
}

//修改速度
let showSpeedFlag = ref(false)
let speedPower = ref('1x')
const showSpeed = () => {
    showSpeedFlag.value = !showSpeedFlag.value
}

const changeSpanSpeed = (speedPowerName: string) => {
    speedPower.value = speedPowerName
    audio = document.querySelector('audio') as HTMLAudioElement
    let rate = Number(speedPower.value.substring(0, speedPower.value.length - 1))
    audio.playbackRate = rate
    console.log(audio.playbackRate);
}

//打开播放列表
let PlayListPanelFlag = ref(false)
const showPlayListPanel = () => {
    PlayListPanelFlag.value = !PlayListPanelFlag.value
}

//清空播放列表
const clearList = () => {
    audio = document.querySelector('audio') as HTMLAudioElement
    audio.pause()
    stopOrPlayFlag.value = true
    audioPlayFlag.value = false
    endTime.value = dayjsSMMSS(0)
}

//按键监视
const keyDownWatch = (e: KeyboardEvent) => {
    if (e.ctrlKey) {
        if (e.code == 'ArrowRight') {
            nextSongThor();
        } else if (e.code == 'ArrowLeft') {
            prevSong();
        } else if (e.code == 'KeyP') {
            changPlayStatus();
        }
    }
    if (e.code == 'Space') {
        changPlayStatus();
    }
}

//主进程播放
onMounted(() => {
    electronIpc.ipcOn('main-prev', () => {
        if (playingList.value.length != 0) {
            console.log('上一首');
            prevSongThor();
        }
    })
    electronIpc.ipcOn('main-next', () => {
        if (playingList.value.length != 0) {
            console.log('下一首');
            nextSongThor();
        }
    })
    electronIpc.ipcOn('main-play', () => {
        if (playingList.value.length != 0) {
            console.log('播放');
            changPlayStatus();
        } else {
            electronIpc.ipcSend('render-play-fail')
        }
    })
    electronIpc.ipcOn('main-stop', () => {
        if (playingList.value.length != 0) {
            console.log('暂停');
            changPlayStatus();
        }
    })

})

//垃圾桶
let rubishFlag = toRef(globalVar, 'rubishFlag')
const rubish = () => {
    rubishFlag.value = true
}

</script>

<style lang="less" scoped>
.noDrag {
    cursor: pointer;
}

.MusicRadio {
    user-select: none;
    width: 100vw;
    height: 70px;
    box-sizing: border-box;
    border-top: 1px solid;
    border-top-color: @split-line-color;
    background-color: @radio-bk-color;
    position: fixed;
    bottom: 0px;
    left: 0px;
    z-index: 12;
    display: flex;
    justify-content: space-between;

    >.left {
        width: 350px;
        height: 100%;
        overflow: hidden;

        &>div {
            height: 100%;
            display: flex;
            align-items: center;

            .image {
                padding: 0px 10px;
                width: 50px;
                height: 50px;
                position: relative;

                :deep(.el-image-hover) {
                    filter: blur(1px) contrast(90%) grayscale(10%);
                    cursor: pointer;
                }

                :deep(.el-image) {
                    padding: 0px 10px;
                    width: 51px;
                    height: 51px;
                    position: absolute;
                    left: -1px;
                    top: -1px;
                    cursor: pointer;

                    img {
                        border-radius: 0.2em;
                    }

                    .el-image__placeholder {
                        width: 49px;
                        height: 50px;
                        background-image: url('@/../image/cloudmusic_5e9Ef54bbN.png');
                        background-repeat: no-repeat;
                        margin-left: 5px;
                        transform: translate(5px, 1px);
                    }

                    .el-image__error {
                        background-color: rgba(0, 0, 0, 0);
                    }
                }

                .active {
                    display: block !important;
                }

                .active-flex {
                    display: flex !important;
                }

                .mask {
                    width: 52px;
                    height: 52px;
                    position: absolute;
                    left: -1px;
                    margin-left: 10px;
                    top: -1px;
                    background-color: rgba(0, 0, 0, .4);
                    border-radius: 0.2em;
                    display: none;
                    cursor: pointer;
                    justify-content: center;
                    align-items: center;

                    i {
                        color: white;
                        display: none;
                    }

                    .icon-shangxiajiantou {
                        font-size: 30px;
                    }
                }
            }

            .txt {
                .name {
                    height: 18px;
                    max-width: 150px;
                    color: @font-color;
                    margin-bottom: 5px;
                    overflow: hidden;
                    display: flex;
                    font-size: 15px;

                    .name-txt {
                        user-select: none;
                        cursor: pointer;
                        width: auto;
                        height: 100%;
                        display: inline-block;
                        white-space: nowrap;
                        margin-right: 10px;

                        >.small {
                            color: @small-font-color;
                        }
                    }
                }

                .t {
                    position: relative;

                    .iconfont {
                        position: absolute;
                        right: -20px;
                        top: 0px;
                        cursor: pointer;

                    }

                    .icon-aixin {
                        color: @small-font-color;

                        &:hover {
                            color: @small-font-color-hover !important;
                        }
                    }

                    .icon-aixin_fill {
                        color: @small-font-red;
                    }
                }

                .singer {
                    max-width: 150px;
                    margin-top: 5px;
                    color: @font-color;
                    font-size: 13px;
                    cursor: pointer;
                    user-select: none;
                    white-space: nowrap;
                    overflow: hidden;

                    >span {
                        display: inline-block;
                        padding-right: 15px;
                    }
                }
            }
        }

        .showOption {
            display: flex;
            align-items: center;
            justify-content: space-around;

            >.left {
                height: 40px;
                width: 40px;
                display: flex;
                justify-content: center;
                align-items: center;

                i {
                    color: @font-color;
                    cursor: pointer;
                }
            }

            >.right {
                display: flex;
                margin-right: 15px;

                >.todo {
                    height: 40px;
                    width: 40px;
                    margin: 0px 5px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    border-radius: 50%;
                    border: 1px solid @audio-border-color;

                    &:hover {
                        background-color: @span-color-hover !important;
                    }
                }

                .icon-aixin_fill {
                    color: #ec4141;
                }

                i {
                    color: @font-color;
                    font-size: 20px;
                }
            }
        }

        .imgpng-leave-from,
        .imgpng-enter-to {
            transform: translateY(0px);
        }

        //开始过度了
        .imgpng-leave-active,
        .imgpng-enter-active {
            transition: all 0.5s ease-in-out;
        }

        //过度完成
        .imgpng-leave-to,
        .imgpng-enter-from {
            transform: translateY(120px);
        }

        .option-enter-from,
        .option-leave-to {
            transform: translateY(-150px);
        }

        //开始过度了
        .option-enter-active,
        .option-leave-active {
            transition: all 0.5s ease-in-out;
        }

        //过度完成
        .option-enter-to,
        .option-leave-from {
            transform: translateY(-70px);
        }

    }

    .readioOption {
        width: 480px;
        height: 100%;
        margin: 0 auto;

        // background-color: yellow;
        .top {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 65%;
            height: 60%;
            // background-color: green;
            margin: 7px auto;

            >div {
                margin: 15px 15px;
            }

            .start {
                .bk {
                    width: 35px;
                    height: 35px;
                    border-radius: 50%;
                    background-color: @stop-btn-bk;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                }
            }

            .before,
            .next {
                transform: scale(1.5, 1.3);
            }

            .ci {
                // font-weight: bolder;
                position: relative;

                .icon-openci-copy {
                    position: absolute;
                    right: -5px;
                    bottom: -5px;
                }
            }

            .open-ci {
                color: @primary-color;
            }

            .active {
                &:hover {
                    color: @primary-color;
                    cursor: pointer;
                }
            }
        }

        .bottom {
            width: 100%;
            height: 10px;
            margin: -7px auto;
            display: flex;
            align-items: center;
            justify-content: center;
            color: @small-font-color;
            font-size: 10px;
            user-select: none;

            .audio-line {
                width: 85%;
                height: 3px;
                background-color: @play-line-bk;
                border-radius: 1em;
                position: relative;
                z-index: 2;
                margin: 2px auto;

                &:hover {
                    height: 5px;
                }

                &:hover .line-loading,
                .line-play {
                    height: 5px;
                }

                &:hover .line-play {
                    height: 5px;
                }

                &:hover .block {
                    display: block;
                }

                // 加载线
                .line-loading {
                    background-color: @play-line-loading;
                    border-radius: 1em;
                    width: 0%;
                    height: 3px;
                    position: absolute;
                    left: 0;
                    top: 0;
                    z-index: 3;
                }

                //播放线
                .line-play {
                    background-color: @primary-color;
                    border-radius: 1em;
                    width: 0%;
                    height: 3px;
                    position: absolute;
                    left: 0;
                    top: 0;
                    z-index: 4;
                }

                .block {
                    position: absolute;
                    left: 0;
                    top: -2px;
                    z-index: 4;
                    height: 9px;
                    width: 9px;
                    border-radius: 50%;
                    background-color: @primary-color;
                    display: none;

                    &:hover {
                        box-shadow: 0px 0px 5px white;
                    }
                }
            }
        }

        .stop {
            color: @stop-color-display !important;
        }

        .can {
            color: @font-color;
        }
    }

    >.right {
        width: 350px;
        height: 70px;
        // background-color: red;
        display: flex;
        align-items: center;
        justify-content: end;

        >div {
            margin: 0px 15px;
            color: @font-color;
        }

        >:last-child {
            margin-right: 20px;
        }

        .playLevel,
        .playSpeed {
            user-select: none;
            font-size: 12px;
            cursor: pointer;

            .bk {
                min-width: 20px;
                width: auto;
                height: 15px;
                text-align: center;
                line-height: 15px;
                border: 1px solid @font-color;
                border-radius: 0.2em;
                padding-left: 2px;
                padding-right: 2px;
            }
        }

        .playList {
            cursor: pointer;
        }

        .shengyin {
            position: relative;
            z-index: 10;

            i {
                cursor: pointer;
            }

            .shengyin-line {
                position: absolute;
                left: -7px;
                top: -110px;
                height: 100px;
                width: 30px;
                background-color: @shengyin;
                border: 1px solid @split-line-color;
                box-shadow: @shadow;
                border-radius: 0.2em;
                display: flex;
                justify-content: center;
                align-items: center;

                &::after {
                    content: '';
                    display: block;
                    height: 0px;
                    width: 0px;
                    margin: 0 auto;
                    position: absolute;
                    bottom: -10px;
                    left: 0px;
                    right: 0px;
                    border-left: 8px rgba(0, 0, 0, 0) solid;
                    border-right: 8px rgba(0, 0, 0, 0) solid;
                    border-top: 6px @shengyin solid;
                    border-bottom: 6px rgba(0, 0, 0, 0) solid;
                }

                .hua {
                    height: 80%;
                    width: 4px;
                    background-color: @play-line-loading;
                    border-radius: 0.2em;
                    position: relative;

                    .liang {
                        width: 4px;
                        border-radius: 0.2em;
                        height: 0%;
                        position: absolute;
                        bottom: 0;
                        left: 0;
                        background-color: @primary-color;

                        &>.point {
                            width: 10px;
                            height: 10px;
                            position: absolute;
                            top: -5px;
                            left: -3px;
                            border-radius: 50%;
                            background-color: @primary-color;
                            // background-color: rgba(0, 0, 0, .5);

                        }
                    }


                }
            }
        }
    }
}

.songDetail-enter-from,
.songDetail-leave-to {
    transform: translateY(100vh);
}

//开始过度了
.songDetail-enter-active,
.songDetail-leave-active {
    transition: all 0.2s linear;
}

//过度完成
.songDetail-enter-to,
.songDetail-leave-from {
    transform: translateY(0);
}
</style>